package com.earthchen.mattress.mqtt;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.eclipse.paho.client.mqttv3.MqttException;


/**
 * 发送消息线程
 *
 * @author earthchen
 * @date 2018/10/24
 **/
public class SendMsgThread extends Thread {

    private ServerMQTT serverMQTT;

    private String topic;

    private Object object;

    public SendMsgThread(ServerMQTT server, String topic, Object obj) {
        this.serverMQTT = server;
        this.topic = topic;
        this.object = obj;
    }

    @Override
    public void run() {
        ObjectMapper mapper = new ObjectMapper();
        String json = null;
        try {
            json = mapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        try {
            serverMQTT.publish("/World", json);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }
}
